import { Injectable, OnApplicationBootstrap } from '@nestjs/common';

@Injectable()
export class EventEmitterReadinessWatcher implements OnApplicationBootstrap {
  private isReady = false;
  private readyPromise: Promise<void>;
  private resolveReady: () => void;

  constructor() {
    const { promise, resolve } = Promise.withResolvers();
    this.readyPromise = promise as Promise<void>;
    this.resolveReady = resolve as () => void;
  }

  // 当应用启动完成时调用
  async onApplicationBootstrap() {
    this.isReady = true;
    this.resolveReady();
  }

  // 等待事件系统准备就绪
  async waitUntilReady(): Promise<void> {
    if (this.isReady) {
      return Promise.resolve();
    }
    return this.readyPromise;
  }
}
